package com.etone.smartAudit.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.AdminRole;
import com.etone.smartAudit.dto.admin.AdminRoleDTO;
import com.etone.smartAudit.dto.admin.FindAdminDTO;
import com.etone.smartAudit.dto.adminMenu.MenuPermissionDTO;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.AdminMapper;
import com.etone.smartAudit.mapper.AdminRoleMapper;
import com.etone.smartAudit.mapstruct.AdminRoleMapstruct;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.admin.AdminListVO;
import com.etone.smartAudit.vo.adminRole.AdminRoleListVO;
import com.etone.smartAudit.vo.adminRole.AdminRoleVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: 蒋学伟
 * @create: 2020-06-07 18:04:08
 * @Description 角色
 */
@Service
@AllArgsConstructor
public class AdminRoleService {

    private AdminRoleMapper adminRoleMapper;

    private AdminRoleMapstruct adminRoleMapstruct;

    private AdminMapper adminMapper;

    /**
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<AdminRoleListVO> list(String name, int page, int pageSize) {
        Page<AdminRoleListVO> adminRoleVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() ->
                adminRoleMapper.findAdminRoleListVO(name)
        );

        return PagerVO.of(adminRoleVOPage);
    }

    public AdminRole get(Integer id) {
        AdminRole adminRole = adminRoleMapper.selectById(id);
        if (adminRole == null) {
            throw new CustomParameterizedException("角色不存在");
        }
        return adminRole;
    }

    /**
     * 创建｜编辑角色
     *
     * @param adminRoleDTO
     * @param id
     * @param admin
     */
    public void save(AdminRoleDTO adminRoleDTO, Integer id, Admin admin) {
        AdminRole adminRole;
        Date now = new Date();
        if (id != null && id > 0) {
            //编辑
            adminRole = get(id);
            adminRole.setUpdateAdminId(admin.getId());
            adminRole.setUpdateTime(now);
            adminRoleMapstruct.copyToAdmin(adminRole, adminRoleDTO);
            adminRoleMapper.updateById(adminRole);

        } else {
            //新增
            adminRole = AdminRole.builder().createAdminId(admin.getId()).createTime(now).build();
            adminRoleMapstruct.copyToAdmin(adminRole, adminRoleDTO);
            adminRoleMapper.insert(adminRole);
        }

    }

    /**
     * 删除
     *
     * @param id
     * @param checkAdmin 检查管理员是否拥有此角色
     */
    public void delete(Integer id, boolean checkAdmin) {
        if (checkAdmin) {
            checkAdmin(id);
        }
        adminRoleMapper.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @param checkAdmin 检查管理员是否拥有此角色
     */
    public void delete(List<Integer> ids, boolean checkAdmin) {
        if (checkAdmin) {
            ids.forEach(id -> checkAdmin(id));
        }
        adminRoleMapper.deleteBatchIds(ids);
    }

    /**
     * 检查角色是否拥有菜单
     *
     * @param roleId
     */
    private void checkAdmin(Integer roleId) {
        List<AdminListVO> adminListVOS = adminMapper.findList(FindAdminDTO.builder().roleId(roleId).build());
        if (!CollectionUtils.isEmpty(adminListVOS)) {
            String adminNickName = adminListVOS.stream().map(adminListVO -> adminListVO.getNickName()).collect(Collectors.joining(","));
            throw new CustomParameterizedException(adminNickName + "拥有" + adminListVOS.get(0).getRoleName() + "角色，无法删除！");
        }
    }

    /**
     * 修改管理员权限
     *
     * @param id
     * @param menumPDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRolePermissions(Integer id, List<MenuPermissionDTO> menumPDto) {
        //删除管理员权限
        adminRoleMapper.deleteRolePermission(id);

        if (!CollectionUtils.isEmpty(menumPDto)) {
            //批量新增管理员权限
            adminRoleMapper.batchInsertPermission(id, menumPDto);
        }
    }

    public AdminRoleVO detail(Integer id) {
        AdminRole adminRole = get(id);
        return adminRoleMapstruct.getAdminRoleVO(adminRole);
    }

    /**
     * 修改管理员菜单
     *
     * @param id
     * @param menuIds
     */
    public void updateRoleMenus(Integer id, List<Integer> menuIds) {
        //删除管理员权限
        adminRoleMapper.deleteRoleMenu(id);

        if (!CollectionUtils.isEmpty(menuIds)) {
            //批量新增管理员权限
            adminRoleMapper.batchInsertMenu(id, menuIds);
        }
    }

    /***
     * 获取角色
     * @param vcCode
     * @return
     */
    public AdminRole getRoleByCode(String vcCode) {
        LambdaQueryWrapper<AdminRole> query = new LambdaQueryWrapper<>();
        query.eq(AdminRole::getCode, vcCode);
        AdminRole role = adminRoleMapper.selectOne(query);
        return role;
    }

    /***
     * 获取菜单ids 通过角色id和权限id
     * @param valueOf
     * @param roleId
     * @return
     */
    public  List<Map<String,Object>>getmenuIdsByRoleIdAndPermissionId(Integer roleId, Integer permisssionId) {
        List<Map<String,Object>> map = adminRoleMapper.getmenuIdsByRoleIdAndPermissionId(roleId,permisssionId);
//        return menuIds;
        return map;
    }
}
